/*
 * @Author: LF
 * @Description: 话题详情页
 * @Date: 2020-10-21 08:38:38
 * @LastEditTime: 2020-10-23 08:58:18
 */
/* eslint-disable */
import React, { Component } from 'react'
// 引入消息框，弹出框，气泡框和返回顶部组件
import { message, Modal, BackTop, Popover } from 'antd'
const { confirm } = Modal
import jwt from 'jsonwebtoken'
// 引入时间格式化的函数
import moment from 'moment'
import { getTopicDetail, publishComment, deleteComment } from '@/services/topic'
import { createChatRoom } from '@/services/chat'
// 引入富文本编辑器
import E from 'wangeditor'
// 引入表情配置项
import { emjImg } from '../config'
// 引入富文本编辑器上传图片的地址
import { uploadImgURL } from '../config'
import WeiboIcon from '../components/shareIcon/weibo'
import QqfriendIcon from '../components/shareIcon/qqfriend'
import DoubanIcon from '../components/shareIcon/douban'
import QqspaceIcon from '../components/shareIcon/qqspace'

export default class topic extends Component {
  constructor(props) {
    super(props)

    this.state = {
      // 帖子信息
      topicData: {},
      // 评论区信息
      comment: [],
      // 个人评论数据
      comment_value: '',
      // 选择聊天的用户id
      collect_user_id: ''
    }
  }
  
  componentDidMount() {
    // 进入页面自动获取数据
    this.getTopicData()
    const elemMenu = this.refs.editorElemMenu
    const elemBody = this.refs.editorElemBody
    const editor = new E(elemMenu, elemBody)

    if (!sessionStorage.getItem('token')) {
      editor.config.placeholder = '登录后才能发表评论哦'
      editor.disable()
    } else {
      editor.config.placeholder = '请输入内容'
    }

    // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
    editor.config.onchange = (html) => {
      this.setState({
        comment_value: editor.txt.html()
      })
    }
    editor.config.menus = [
      'emoticon', // 表情
      'image' // 插入图片
    ]
    editor.config.uploadImgServer = uploadImgURL
    editor.config.uploadFileName = 'file'
    // 表情配置项
    editor.config.emotions = [
      {
        title: '表情',
        type: 'image',
        content: emjImg
      }
    ]
    // 将token加到上传图片请求头中
    editor.config.uploadImgHeaders = {
      token: sessionStorage.getItem('token')
    }
    // 实例化富文本编辑器
    editor.create()
  }

  // 获取话题具体数据
  getTopicData = async () => {
    let { data: res } = await getTopicDetail({
      params: { id: this.props.match.params.id }
    })
    if (res && res.ok === 1) {
      document.title = res.data.title + ' - ' + document.title
      this.setState({
        topicData: res.data,
        comment: res.comment
      })
    }
  }

  // 提交评论
  commentSubmit = async () => {
    // 表单校验
    if (this.state.comment_value.trim() === '') {
      return message.error('不能提交空评论！')
    }
    // 发起提交评论请求
    let { data: res } = await publishComment({
      topic_id: this.props.match.params.id,
      value: this.state.comment_value,
      create_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    })
    // 提交评论成功后
    if (res && res.ok === 1) {
      // 重新获取页面数据
      this.getTopicData()
      // 将评论框的内容置空
      document.querySelector('.w-e-text').innerHTML = ''
      // 将state数据中的评论置空
      this.setState({
        comment_value: ''
      })
    } else {
      message.error(res.msg)
    }
  }

  // 删除评论
  delComment = (id) => {
    // 删除前的确认
    confirm({
      okText: '确认',
      cancelText: '取消',
      title: '确定要删除评论吗？',
      // 确认删除后
      onOk: async () => {
        // 发起请求
        let { data: res } = await deleteComment({ params: { id } })
        // 删除评论成功后
        if (res && res.ok === 1) {
          // 重新获取数据
          this.getTopicData()
          // 提示成功
          message.success('删除成功')
        }
      }
    })
  }

  // 创建私聊房间
  createRoom = async () => {
    // 发起请求获取聊天对象的信息
    let { data: res } = await createChatRoom({
      collect_user_id: this.state.collect_user_id
    })
    // 请求成功后
    if (res && res.ok === 1 && res.data) {
      // 在浏览器存储聊天对象的信息，到了聊天页后取出，即可直接显示与该聊天对象的对话框
      sessionStorage.setItem('chatingUser', JSON.stringify(res.data))
      // 随后跳转到聊天页
      window.location.href = '/myMessage'
    }
  }

  render() {
    const author_content = (
      <div style={{ cursor: 'pointer' }} onClick={this.createRoom}>
        发消息
      </div>
    )
    const content = (
      <div style={{ cursor: 'pointer' }} onClick={this.createRoom}>
        发消息
      </div>
    )
    // 循环评论区评论数据
    let comment_arr = []
    this.state.comment.forEach((item, index) => {
      comment_arr.push(
        <div key={index} className="comment-realBox">
          {item.avatar ? (
            <img className="comment-user-avatar" src={item.avatar} />
          ) : (
            <img
              style={{ width: '30px', height: '30px' }}
              className="comment-user-avatar"
              src={require('../static/images/empty-avatar.png')}
            />
          )}
          <div className="comment-head">
            {!sessionStorage.getItem('token') && <span>{item.username}</span>}
            {sessionStorage.getItem('token') &&
              item.user_id ===
                jwt.decode(sessionStorage.getItem('token')).id && (
                <span>{item.username}</span>
              )}
            {sessionStorage.getItem('token') &&
              item.user_id !==
                jwt.decode(sessionStorage.getItem('token')).id && (
                <Popover content={content} trigger="click">
                  <span
                    onClick={() => {
                      this.setState({
                        collect_user_id: item.user_id
                      })
                    }}
                  >
                    {item.username}
                  </span>
                </Popover>
              )}
            <span>
              {moment(item.create_time).format('YYYY-MM-DD HH:mm:ss')}
            </span>
            <span>{index + 1}</span>
          </div>
          <div
            className="comment-body"
            dangerouslySetInnerHTML={{
              __html: item.value
            }}
          />
          {sessionStorage.getItem('token') !== null &&
            item.user_id == jwt.decode(sessionStorage.getItem('token')).id && (
              <a
                className="btn del-comment"
                onClick={() => this.delComment(item.id)}
              >
                删除评论
              </a>
            )}
        </div>
      )
    })
    return (
      <div>
        <div className="center-nav">
          <div className="center-nav-left">
            <div className="card-head">
              <h1>{this.state.topicData.title}</h1>
              <div className="froumn-msg topic-msg">
                <span>{this.state.topicData.name}</span> ·{' '}
                {!sessionStorage.getItem('token') && (
                  <span>{this.state.topicData.username}</span>
                )}
                {sessionStorage.getItem('token') &&
                  this.state.topicData.author_id ===
                    jwt.decode(sessionStorage.getItem('token')).id && (
                    <span>{this.state.topicData.username}</span>
                  )}
                {sessionStorage.getItem('token') &&
                  this.state.topicData.author_id !==
                    jwt.decode(sessionStorage.getItem('token')).id && (
                    <Popover content={author_content} trigger="click">
                      <span
                        onClick={() => {
                          this.setState({
                            collect_user_id: this.state.topicData.author_id
                          })
                        }}
                      >
                        {this.state.topicData.username}
                      </span>
                    </Popover>
                  )}
                ·{' '}
                {moment(this.state.topicData.create_time).format(
                  'YYYY-MM-DD HH:mm:ss'
                )}
              </div>
              <div className="share-box">
                <WeiboIcon title={this.state.topicData.title} />
                <QqfriendIcon title={this.state.topicData.title} />
                <DoubanIcon title={this.state.topicData.title} />
                <QqspaceIcon title={this.state.topicData.title} />
              </div>
            </div>
            <div
              className="card-body"
              dangerouslySetInnerHTML={{
                __html: this.state.topicData.value
              }}
            />
            {this.state.topicData.comment_num !== 0 && (
              <div className="comment-msg-box">
                <div className="comment-msg-box-head">
                  {this.state.topicData.comment_num}条评论
                </div>
                {comment_arr}
              </div>
            )}
            <div className="comment-box">
              <div className="comment-box-head">发表评论</div>
              <div className="comment-box-body">
                <div className="shop">
                  <div className="text-area">
                    <div
                      ref="editorElemMenu"
                      style={{
                        backgroundColor: '#f1f1f1',
                        border: '1px solid #ccc'
                      }}
                      className="editorElem-menu"
                    ></div>
                    <div
                      style={{
                        overflowY: 'auto',
                        height: 250,
                        border: '1px solid #ccc',
                        borderTop: 'none'
                      }}
                      ref="editorElemBody"
                      className="editorElem-body"
                    ></div>
                  </div>
                </div>
                <a
                  style={{ marginTop: '1rem' }}
                  className="btn"
                  onClick={this.commentSubmit}
                >
                  评论
                </a>
              </div>
            </div>
          </div>
          <div className="center-nav-right"></div>
        </div>
        <BackTop />
      </div>
    )
  }
}
